<template>
  <div class="student-detail">
    <el-page-header @back="router.back()" title="返回">
      <template #content>
        <span class="page-title">学生详情</span>
      </template>
      <template #extra>
        <el-button type="primary" class="no-print" @click="handlePrint">
          <el-icon><Printer /></el-icon>
          打印
        </el-button>
      </template>
    </el-page-header>
    
    <div id="printArea" v-loading="loading" style="margin-top: 20px;">
      <!-- 基本信息 -->
      <el-card>
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        
        <el-descriptions :column="3" border v-if="student">
          <el-descriptions-item label="学号">{{ student.studentId }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ student.name }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ student.gender }}</el-descriptions-item>
          <el-descriptions-item label="出生日期">{{ formatDate(student.birthDate) }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ calculateAge(student.birthDate) }}岁</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ maskIdCard(student.idCard) }}</el-descriptions-item>
          <el-descriptions-item label="专业">{{ student.major }}</el-descriptions-item>
          <el-descriptions-item label="班级">{{ student.className }}</el-descriptions-item>
          <el-descriptions-item label="年级">{{ student.grade }}</el-descriptions-item>
          <el-descriptions-item label="入学日期">{{ formatDate(student.enrollmentDate) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(student.status)">
              {{ getStatusText(student.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ student.phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="邮箱" :span="2">{{ student.email || '-' }}</el-descriptions-item>
          <el-descriptions-item label="地址" :span="3">{{ student.address || '-' }}</el-descriptions-item>
          <el-descriptions-item label="紧急联系人">{{ student.emergencyContact || '-' }}</el-descriptions-item>
          <el-descriptions-item label="紧急联系电话" :span="2">{{ student.emergencyPhone || '-' }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
      
      <!-- 成绩信息 -->
      <el-card style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>成绩信息</span>
            <el-button
              v-if="userStore.checkPermission(Permission.GRADE_MANAGE)"
              type="primary"
              size="small"
              class="no-print"
              @click="showAddGradeDialog = true"
            >
              添加成绩
            </el-button>
          </div>
        </template>
        
        <el-table :data="grades" stripe>
          <el-table-column prop="semester" label="学期" width="120" />
          <el-table-column prop="courseName" label="课程名称" width="150" />
          <el-table-column prop="courseCode" label="课程代码" width="120" />
          <el-table-column prop="credit" label="学分" width="80" />
          <el-table-column prop="score" label="成绩" width="80" />
          <el-table-column prop="examType" label="考试类型" width="100" />
          <el-table-column prop="teacherName" label="任课教师" width="100" />
          <el-table-column label="操作" width="150" class="no-print">
            <template #default="{ row }">
              <el-button
                v-if="userStore.checkPermission(Permission.GRADE_MANAGE)"
                type="warning"
                size="small"
                link
                @click="handleEditGrade(row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="userStore.checkPermission(Permission.GRADE_MANAGE)"
                type="danger"
                size="small"
                link
                @click="handleDeleteGrade(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 奖励信息 -->
      <el-card style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>奖励信息</span>
            <el-button
              v-if="userStore.checkPermission(Permission.REWARD_MANAGE)"
              type="primary"
              size="small"
              class="no-print"
              @click="showAddRewardDialog = true"
            >
              添加奖励
            </el-button>
          </div>
        </template>
        
        <el-table :data="rewards" stripe>
          <el-table-column prop="type" label="类型" width="150" />
          <el-table-column prop="name" label="名称" width="200" />
          <el-table-column prop="level" label="级别" width="100" />
          <el-table-column prop="awardDate" label="获奖日期" width="120">
            <template #default="{ row }">
              {{ formatDate(row.awardDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="说明" />
          <el-table-column label="操作" width="150" class="no-print">
            <template #default="{ row }">
              <el-button
                v-if="userStore.checkPermission(Permission.REWARD_MANAGE)"
                type="warning"
                size="small"
                link
                @click="handleEditReward(row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="userStore.checkPermission(Permission.REWARD_MANAGE)"
                type="danger"
                size="small"
                link
                @click="handleDeleteReward(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 惩罚信息 -->
      <el-card style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>惩罚信息</span>
            <el-button
              v-if="userStore.checkPermission(Permission.PUNISHMENT_MANAGE)"
              type="primary"
              size="small"
              class="no-print"
              @click="showAddPunishmentDialog = true"
            >
              添加惩罚
            </el-button>
          </div>
        </template>
        
        <el-table :data="punishments" stripe>
          <el-table-column prop="type" label="类型" width="120" />
          <el-table-column prop="reason" label="原因" width="200" />
          <el-table-column prop="date" label="日期" width="120">
            <template #default="{ row }">
              {{ formatDate(row.date) }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="说明" />
          <el-table-column prop="revokeDate" label="撤销日期" width="120">
            <template #default="{ row }">
              {{ row.revokeDate ? formatDate(row.revokeDate) : '-' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" class="no-print">
            <template #default="{ row }">
              <el-button
                v-if="userStore.checkPermission(Permission.PUNISHMENT_MANAGE)"
                type="warning"
                size="small"
                link
                @click="handleEditPunishment(row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="userStore.checkPermission(Permission.PUNISHMENT_MANAGE)"
                type="danger"
                size="small"
                link
                @click="handleDeletePunishment(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Printer } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { Student, Grade, Reward, Punishment, Permission, StudentStatus } from '@/types'
import { getStudentDetail } from '@/api/student'
import { getStudentGrades, deleteGrade } from '@/api/grade'
import { getStudentRewards, deleteReward } from '@/api/reward'
import { getStudentPunishments, deletePunishment } from '@/api/punishment'
import { formatDate, maskIdCard, calculateAge } from '@/utils/format'
import { printElement } from '@/utils/print'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const student = ref<Student>()
const grades = ref<Grade[]>([])
const rewards = ref<Reward[]>([])
const punishments = ref<Punishment[]>([])

const showAddGradeDialog = ref(false)
const showAddRewardDialog = ref(false)
const showAddPunishmentDialog = ref(false)

const studentId = Number(route.params.id)

const getStatusTagType = (status: StudentStatus) => {
  const typeMap: Record<StudentStatus, any> = {
    [StudentStatus.ENROLLED]: 'success',
    [StudentStatus.GRADUATED]: 'info',
    [StudentStatus.SUSPENDED]: 'warning',
    [StudentStatus.EXPELLED]: 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status: StudentStatus) => {
  const textMap: Record<StudentStatus, string> = {
    [StudentStatus.ENROLLED]: '在读',
    [StudentStatus.GRADUATED]: '毕业',
    [StudentStatus.SUSPENDED]: '休学',
    [StudentStatus.EXPELLED]: '退学'
  }
  return textMap[status] || '未知'
}

const fetchStudentDetail = async () => {
  loading.value = true
  try {
    student.value = await getStudentDetail(studentId)
  } catch (error) {
    console.error('获取学生详情失败:', error)
  } finally {
    loading.value = false
  }
}

const fetchGrades = async () => {
  try {
    grades.value = await getStudentGrades(studentId)
  } catch (error) {
    console.error('获取成绩信息失败:', error)
  }
}

const fetchRewards = async () => {
  try {
    rewards.value = await getStudentRewards(studentId)
  } catch (error) {
    console.error('获取奖励信息失败:', error)
  }
}

const fetchPunishments = async () => {
  try {
    punishments.value = await getStudentPunishments(studentId)
  } catch (error) {
    console.error('获取惩罚信息失败:', error)
  }
}

const handlePrint = () => {
  printElement('printArea')
}

const handleEditGrade = (row: Grade) => {
  // TODO: 实现编辑成绩
  console.log('编辑成绩:', row)
}

const handleDeleteGrade = async (row: Grade) => {
  try {
    await deleteGrade(row.id)
    ElMessage.success('删除成功')
    fetchGrades()
  } catch (error) {
    console.error('删除成绩失败:', error)
  }
}

const handleEditReward = (row: Reward) => {
  // TODO: 实现编辑奖励
  console.log('编辑奖励:', row)
}

const handleDeleteReward = async (row: Reward) => {
  try {
    await deleteReward(row.id)
    ElMessage.success('删除成功')
    fetchRewards()
  } catch (error) {
    console.error('删除奖励失败:', error)
  }
}

const handleEditPunishment = (row: Punishment) => {
  // TODO: 实现编辑惩罚
  console.log('编辑惩罚:', row)
}

const handleDeletePunishment = async (row: Punishment) => {
  try {
    await deletePunishment(row.id)
    ElMessage.success('删除成功')
    fetchPunishments()
  } catch (error) {
    console.error('删除惩罚失败:', error)
  }
}

onMounted(() => {
  fetchStudentDetail()
  fetchGrades()
  fetchRewards()
  fetchPunishments()
})
</script>

<style scoped>
.student-detail {
  padding: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

@media print {
  .no-print {
    display: none !important;
  }
}
</style>

